package com.wh.beans.tags;

import com.alibaba.fastjson.JSONObject;

import com.legend.security.PermissionConfig;
import com.legend.security.PermissionItem;
import com.wh.beans.Toolbar;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ToolBar implements TemplateDirectiveModel {

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException,
			IOException {
		try {

			String moduleCode = params.get("moduleCode").toString();
			String id = params.get("id").toString();
			PermissionConfig config = new PermissionConfig();
			List<PermissionItem> lst = config.getPermissionItems(moduleCode);
			if (lst != null && lst.size() > 0) {
				StringBuffer sb = new StringBuffer();
				sb.append("<div id=\"" + id + "\"></div>");
				sb.append("<script type='text/javascript'>");
				sb.append("var barItem=");
				List<Object> tblst = new ArrayList<Object>();
				Toolbar tb;
				int i = 0;
				for (PermissionItem p : lst) {
					if ((p.getPosition() & 4) == 4) {
						i++;
						tb = new Toolbar();
						tb.setText(p.getName());
                        String str=p.getEvent();
                        str=str.replace("[module]",moduleCode);
						tb.setOnclick(str);
						tb.setIconCls(p.getIconCls());
						tblst.add(tb);
						tblst.add("-");
					}
				}
				tblst.remove(i * 2 - 1);
				sb.append(JSONObject.toJSONString(tblst));
				sb.append(";$('#" + id + "').toolbar({items:barItem});");
				sb.append("</script>");

				env.getOut().write(sb.toString());
			} else
				env.getOut().write("");

		} catch (RuntimeException e) {
			env.getOut().write(e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			env.getOut().write(e.getMessage());
		}
	}

	public static void main(String[] args) throws Exception {
		// String str = "status==1?'禁用':'启用'";
		String str = "['启用','禁用','待定'][status]";
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		engine.put("status", 2);
		Object result = engine.eval(str);

		System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);

	}

}
